package com.education.welco.service.impl;

import com.education.common.pojo.AjaxResult;
import com.education.common.utils.Convert;
import com.education.welco.mapper.SysSourcePayMapper;
import com.education.welco.pojo.SysSourcePay;
import com.education.welco.service.ISysSourcePayService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * (用户资源收藏支付) 服务层实现
 *
 * @author d
 * @date 2021-09-08
 */
@Service
public class SysSourcePayServiceImpl implements ISysSourcePayService {

    @Autowired
    private SysSourcePayMapper sysSourcePayMapper;

    /**
     * 查询(用户资源收藏支付)信息
     *
     * @param cUserId (用户资源收藏支付)ID
     * @return (用户资源收藏支付)信息
     */
    @Override
    public List<SysSourcePay> selectSysSourcePayById(Integer cUserId) {
        return sysSourcePayMapper.selectSysSourcePayById(cUserId);
    }

    /**
     * 查询(用户资源收藏支付)列表
     *
     * @param sysSourcePay (用户资源收藏支付)信息
     * @return (用户资源收藏支付)集合
     */
    @Override
    public List<SysSourcePay> selectSysSourcePayList(SysSourcePay sysSourcePay) {
        return sysSourcePayMapper.selectSysSourcePayList(sysSourcePay);
    }

    /**
     * 查询(用户资源收藏支付)列表
     *
     * @param map 根据开始时间和结束时间 类型
     * @return (用户资源收藏支付)集合
     */
    @Override
    public List<Integer> selectSysSourcePayListByTimeAndType(Map<String, Object> map) {
        return sysSourcePayMapper.selectSysSourcePayListByTimeAndType(map);
    }

    /**
     * 新增(用户资源收藏支付)
     *
     * @param sysSourcePay (用户资源收藏支付)信息
     * @return 结果
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int insertSysSourcePay(SysSourcePay sysSourcePay) {
        return sysSourcePayMapper.insertSysSourcePay(sysSourcePay);
    }

    /**
     * 修改(用户资源收藏支付)
     *
     * @param sysSourcePay (用户资源收藏支付)信息
     * @return 结果
     */
    @Override
    public int updateSysSourcePay(SysSourcePay sysSourcePay) {
        return sysSourcePayMapper.updateSysSourcePay(sysSourcePay);
    }

    /**
     * 修改用户资源收藏支付记录的收藏状态
     *
     * @param sysSourcePay 用户资源收藏支付信息
     * @return 结果
     */
    @Override
    public int updateSysSourcePayCollectionStatus(SysSourcePay sysSourcePay) {
        return sysSourcePayMapper.updateSysSourcePayCollectionStatus(sysSourcePay);
    }

    /**
     * 删除(用户资源收藏支付)对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteSysSourcePayByIds(String ids) {
        return sysSourcePayMapper.deleteSysSourcePayByIds(Convert.toStrArray(ids));
    }

    @Override
    public List<SysSourcePay> getSysSourcePayByByUserId(SysSourcePay sysSourcePay) {
        return sysSourcePayMapper.getSysSourcePayByByUserId(sysSourcePay);
    }

    @Override
    public AjaxResult getUserSysSourcePayList(SysSourcePay sysSourcePay) {
        PageHelper.startPage(Integer.valueOf(sysSourcePay.getPageNum()), Integer.valueOf(sysSourcePay.getPageSize()));
        List<SysSourcePay> sysSourcePayList = sysSourcePayMapper.getSysSourcePayByByUserId(sysSourcePay);
        PageInfo pageInfo = new PageInfo<>(sysSourcePayList);
        return AjaxResult.success().put("data", pageInfo).put("list", sysSourcePayList);
    }

    //@Override
    //public String getUserViewPre(Integer cWatchKeyid) {
    //    return sysWatchHitoryMapper.getUserViewPre(cWatchKeyid);
    //}

    /**
     * pc 端查询我的收藏
     * @param cUserId 用户id主键
     * @param pageNum 第几页
     * @param pageSize 每页条数
     * @param catalogId 课程主键id  不同资源可能对应不同的目录级别的课程id
     * @param cResourceType 资源类型 1 课程 2 试题  3 资源  4 文章
     * @return
     */
    /*@Override
    public PageInfo<SysMyCollectionRESQ> selectMyCollection(Integer cUserId,Integer cResourceType,
                                                            Integer pageNum, Integer pageSize,
                                                            Integer catalogId, String title) {
        List<SysMyCollectionRESQ> resqList = new ArrayList<>();
        if(pageNum != null && pageSize != null){
            PageHelper.startPage(pageNum, pageSize);
        }
        //根据查询的资源类型进行查询相应字段
        //1、课程
        if(StatusEnum.ONE.value.equals(cResourceType)){
            resqList = sysSourcePayMapper.selectMyCollectionJoinCatalog(cResourceType, StatusEnum.ONE.value, cUserId, catalogId);
        }
        //2、试题
        if(StatusEnum.TWO.value.equals(cResourceType)){
            resqList = sysSourcePayMapper.selectMyCollectionJoinQuestion(cResourceType, StatusEnum.ONE.value, cUserId, catalogId);
            //设置所属目录
            for (SysMyCollectionRESQ sysMyCollectionRESQ : resqList) {
                String path = catalogMapper.selectSysCatalogPathByQuestionId(sysMyCollectionRESQ.getResourceId());
                if(!StringUtils.isBlank(path)){
                    sysMyCollectionRESQ.setJoinPath(path);
                }else {
                    sysMyCollectionRESQ.setJoinPath("");
                }
            }

        }
        //3、资源
        if(StatusEnum.THREE.value.equals(cResourceType)){
            resqList = sysSourcePayMapper.selectMyCollectionJoinResource(cResourceType, StatusEnum.ONE.value, cUserId, catalogId);
            //遍历设置
            for (SysMyCollectionRESQ sysMyCollectionRESQ : resqList) {
                // 全路径
                String path = catalogMapper.selectSysCatalogPathByResId(sysMyCollectionRESQ.getResourceId());
                if(!StringUtils.isBlank(path)){
                    sysMyCollectionRESQ.setJoinPath(path);
                }else {
                    sysMyCollectionRESQ.setJoinPath("");
                }
                // 文件后缀
                String resUrl = sysMyCollectionRESQ.getResUrl();
                if(!StringUtils.isBlank(resUrl) && resUrl.contains(".")){
                    sysMyCollectionRESQ.setFileSuffix(resUrl.split("\\.")[1]);
                }else {
                    sysMyCollectionRESQ.setFileSuffix("");
                }
                // 下载量
                Integer integer = resDownloadHistoryMapper.selectCountSysResDownloadHistoryByResId(sysMyCollectionRESQ.getResourceId());
                if(null != integer){
                    sysMyCollectionRESQ.setDownloads(integer);
                }else {
                    sysMyCollectionRESQ.setDownloads(0);
                }

                if(sysMyCollectionRESQ.getPrice().compareTo(new BigDecimal(0)) == 0){
                    sysMyCollectionRESQ.setIsFree("1");
                }else {
                    sysMyCollectionRESQ.setIsFree("2");
                }

                String isBuy = sysMyCollectionRESQ.getIsBuy();
                if(StringUtils.isNotBlank(isBuy)) {
                    if ("1".equals(isBuy)) {
                        sysMyCollectionRESQ.setIsFree("3");
                    }
                }

            }
        }
        //4、文章  查询 sys_forums_collection 表中数据
        if(StatusEnum.FOUR.value.equals(cResourceType)){
            //论坛用户收藏表当中文章类型为 3
            cResourceType = StatusEnum.THREE.value;
            resqList = sysSourcePayMapper.selectMyCollectionJoinForums(cResourceType, StatusEnum.ONE.value, cUserId, title, catalogId);
            //格式化封面路径
            for (SysMyCollectionRESQ sysMyCollectionRESQ : resqList) {
                String resIco = sysMyCollectionRESQ.getResIco();
                if(StringUtils.isNotBlank(resIco) && resIco.contains(";")){
                    sysMyCollectionRESQ.setResIco(resIco.split(";")[0]);
                }
            }
        }
        return new PageInfo<>(resqList);
    }*/


    /*@Override
    public List<SysMyCollectionRESQ> selectMyCollectForRes(Integer isFree, Integer resType, Integer userId, List<Integer> list) {
        List<SysMyCollectionRESQ> resqs = sysSourcePayMapper.selectMyCollectionJoinResourceForApp(isFree, resType, userId, list);

        //查询该用户已购买资源
        SysSourcePay sourcePay = new SysSourcePay();
        sourcePay.setCUserId(userId);
        sourcePay.setNIsPay(1);
        sourcePay.setCResourceType(StatusEnum.THREE.type);
        List<SysSourcePay> sourcePays = sysSourcePayMapper.selectSysSourcePayList(sourcePay);
        List<Integer> integerList = sourcePays.stream().map(SysSourcePay::getCResourceId).collect(Collectors.toList());

        for (SysMyCollectionRESQ resq : resqs) {
            //格式化时间
            resq.setCreateTimeStr(DateUtil.formatDate(resq.getCreateTime()));
            //设置是否免费字段
            BigDecimal price = resq.getPrice();
            if(price != null){
                if(price.compareTo(new BigDecimal(0)) == 0){
                    //免费
                    resq.setIsFree(StatusEnum.ONE.type);
                }else {
                    //付费
                    resq.setIsFree(StatusEnum.TWO.type);
                }
            }else {
                //免费
                resq.setIsFree(StatusEnum.ONE.type);
            }

            //设置是否购买
            if(integerList.contains(resq.getResourceId())){
                resq.setIsFree(StatusEnum.THREE.type);
            }

            //设置资源后缀
            String resUrl = resq.getResUrl();
            if(StringUtils.isNotBlank(resUrl)){
                resq.setSuffix(resUrl.split("\\.")[1]);
            }
        }
        return resqs;
    }*/

    /*@Override
    public AjaxResult selectMyCollectForQuestion(String userId, Integer catalogId) {
        //查询该用户所选专业下的任务id数组
        List<SysCatalogDTO> sysCatalogDTOS = catalogService.selectSysCatalogThreeTier(catalogId, "");
        List<Integer> list = new ArrayList<>();
        if(sysCatalogDTOS != null && sysCatalogDTOS.size() > 0){
            for (SysCatalogDTO sysCatalogDTO : sysCatalogDTOS) {
                List<SysCatalogDTO> list1 = sysCatalogDTO.getList();
                if(list1 != null && list1.size() > 0){
                    for (SysCatalogDTO catalogDTO : list1) {
                        List<SysCatalogDTO> list2 = catalogDTO.getList();
                        if(list2 != null && list2.size() > 0){
                            list.addAll(list2.stream().map(SysCatalogDTO::getId).collect(Collectors.toList()));
                        }
                    }
                }
            }
        }

        List<SysMyWrongQuestionResq> resqs = sysSourcePayMapper.selectCatalogListForMyWrongQuestion(Integer.valueOf(userId), list);
        //课程id数组
//        List<Integer> catalogIds = resqs.stream().map(SysMyWrongQuestionResq::getCatalogId).distinct().collect(Collectors.toList());

        Map<Integer,List<SysMyWrongQuestionResq>> map = resqs.stream()
                .filter(d -> d != null && d.getProjectName() != null)
                .collect(Collectors.groupingBy(SysMyWrongQuestionResq::getProjectId));

        //获取map的键 设置为章节名称
        List<MyWrongQuestionListResq> list1 = new ArrayList<>();
        for (Map.Entry<Integer, List<SysMyWrongQuestionResq>> entry : map.entrySet()) {
            MyWrongQuestionListResq wrongQuestionListResq = new MyWrongQuestionListResq();
            List<SysMyWrongQuestionResq> value = entry.getValue();

            String projectName = value.get(0).getProjectName();
            wrongQuestionListResq.setProjectName(projectName);
            wrongQuestionListResq.setList(value);
            list1.add(wrongQuestionListResq);
        }
//        List<MyWrongQuestionListResqForOne> list3 = new ArrayList<>();
//        for (Integer id : catalogIds) {
//            MyWrongQuestionListResqForOne wrongQuestionListResq = new MyWrongQuestionListResqForOne();
//            List<MyWrongQuestionListResq> list2 = new ArrayList<>();
//            //获取到课程id
//            for (MyWrongQuestionListResq myWrongQuestionListResq : list1) {
//                SysMyWrongQuestionResq questionResq = myWrongQuestionListResq.getList().get(0);
//                if(id.equals(questionResq.getCatalogId())){
//                    wrongQuestionListResq.setCatalogName(questionResq.getCatalogName());
//                    list2.add(myWrongQuestionListResq);
//                }
//            }
//            wrongQuestionListResq.setList(list2);
//            list3.add(wrongQuestionListResq);
//        }
        return AjaxResult.success(list1);
    }*/

    /**
     * app 端查询我的收藏 动态、文章列表
     *      用户头像 用户名称 多长时间前 是否关注该用户
     *      标题 内容 点赞数 评论数 收藏数
     * @param userId 用户id
     * @param type 4 文章 5 动态
     * @return 资源列表
     */
    /*@Override
    public List<SysRecommendCircleResq> selectMyCollectForEssay(Integer userId, Integer type) {
        //收藏资源类型    4 文章 5 动态   3 文章 4 动态
        type = type - 1;
        return sysSourcePayMapper.selectMyCollectionJoinForumsForApp(type, StatusEnum.ONE.value, userId);
//        Date date = new Date();
//        for (SysRecommendCircleResq sysMyCollectionRESQ : resqs) {
            //如果是文章的话 进行封面的格式化
//            if(StatusEnum.FIVE.value.equals(type)){
//                String resIco = sysMyCollectionRESQ.getResIco();
//                if(StringUtils.isNotBlank(resIco) && resIco.contains(";")){
//                    sysMyCollectionRESQ.setResIco(resIco.split(";")[0]);
//                }
//            }

            //格式化已发布时间
//            Date createTime = sysMyCollectionRESQ.getCreateTime();
            //分钟
//            long minute = DateUtil.between(createTime, date, DateUnit.MINUTE);
//            if(minute > 60){
//                //小时
//                long hour = DateUtil.between(createTime, date, DateUnit.HOUR);
//                if(hour > 24){
//                    //天
//                    long day = DateUtil.betweenDay(createTime, date, true);
//                    if(day > 30){
//                        //月
//                        long month = DateUtil.betweenMonth(createTime, date, true);
//                        if(month > 12){
//                            long year = DateUtil.betweenYear(createTime, date, true);
//                            sysMyCollectionRESQ.setTimeOut(year + "年前");
//                        }else {
//                            sysMyCollectionRESQ.setTimeOut(month + "月前");
//                        }
//                    }else {
//                        sysMyCollectionRESQ.setTimeOut(day + "天前");
//                    }
//                }else {
//                    sysMyCollectionRESQ.setTimeOut(hour + "小时前");
//                }
//            }else {
//                sysMyCollectionRESQ.setTimeOut(minute + "分钟前");
//            }

//        }
    }*/


}